package cn.com.xinjinfu.pdoulcProduct.activity.recharge;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.utils.EditTextUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.ReloadUserInfo;
import cn.com.xinjinfu.pdoulcProduct.view.PwdEditText;
import cn.com.xinjinfu.pdoulcProduct.view.PwdEditText.OnInputFinishListener;

/**
 * Created by android-adt on 2016/7/25.
 */
public class TradePWD extends BaseActivity {
    private RequestQueue requen;
    private PwdEditText mPetPwd0;
    private PwdEditText mPetPwd;
    private PwdEditText mPetPwd2;
    private LinearLayout ll;
    private TextView tv_next_hint, tv_error_hint, tv_forget_pwd;
    String mPwd;
    String mPwd2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_trade_pwd);

        requen = Volley.newRequestQueue(this);
        mPetPwd0 = (PwdEditText) findViewById(R.id.pet_pwd0);
        mPetPwd = (PwdEditText) findViewById(R.id.pet_pwd);
        mPetPwd2 = (PwdEditText) findViewById(R.id.pet_pwd2);
        tv_next_hint = (TextView) findViewById(R.id.tv_next_hint);
//        tv_next_hint2 = (TextView) findViewById(R.id.tv_next_hint2);
        tv_error_hint = (TextView) findViewById(R.id.tv_error_hint);
        tv_forget_pwd = (TextView) findViewById(R.id.tv_forget_pwd);
        ll = (LinearLayout) findViewById(R.id.ll);

        Intent intent = getIntent();
        int falg = intent.getIntExtra("falg", 0);    //取得id
        if (falg == 1) {
            TitleManager.showTitle(this, "修改交易密码", "");
            tv_next_hint.setText("请输入原密码验证身份");
            tv_forget_pwd.setVisibility(View.VISIBLE);
            mPetPwd0.setVisibility(View.VISIBLE);
            mPetPwd.setVisibility(View.GONE);
            EditTextUtil.setUpSofe(mPetPwd0);
        } else {
            mPetPwd0.setVisibility(View.GONE);
            mPetPwd.setVisibility(View.VISIBLE);
            TitleManager.showTitle(this, "设置交易密码", "");
            EditTextUtil.setUpSofe(mPetPwd);
        }
        /**
         * 第一次输入密码
         */
        mPetPwd.setOnInputFinishListener(new OnInputFinishListener() {
            @Override
            public void onInputFinish(String password) {
                mPwd = password;
                mPetPwd.setVisibility(View.GONE);
                mPetPwd2.setVisibility(View.VISIBLE);
                tv_next_hint.setText("请确认密码");
                hindSoftInput();
            }

            @Override
            public void onInputChanged() {
            }
        });
        /**
         * 支付密码校验，没设置过不会出现
         */
        mPetPwd0.setOnInputFinishListener(new OnInputFinishListener() {
            @Override
            public void onInputFinish(String password) {
                hindSoftInput();
                pwdcheckRequen(password);
            }

            @Override
            public void onInputChanged() {
                tv_error_hint.setText("");
            }
        });
        /**
         * 第二次输入密码
         */
        mPetPwd2.setOnInputFinishListener(new OnInputFinishListener() {
            @Override
            public void onInputFinish(String password) {
                hindSoftInput();
                if (mPwd.equals(password)) {
                    loginRequen();
                } else {
                    tv_error_hint.setText("您两次输入的密码不一样，请重新输入！");
                }
            }

            @Override
            public void onInputChanged() {
                tv_error_hint.setText("");
            }
        });
        tv_forget_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(TradePWD.this, ForgetPayPwdActivity.class));
                ActivityManager.getInstance().addActivity(TradePWD.this);
            }
        });
    }

    public void pwdcheckRequen(String password) {
        final Map<String, String> parameters = DataHandler.getParameters("1403");
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            parameters.put("id", user.getCurrUser().getSign());
        }
        parameters.put("passwd", DataHandler.encrypt3DES(password));
        parameters.put("type", "2");
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jobj) {
                L.i("校验密码返回结果" + jobj.toString());
                if (JSONManager.getError(jobj) == -1) {
                    mPetPwd0.setVisibility(View.GONE);
                    mPetPwd.setVisibility(View.VISIBLE);
                    tv_forget_pwd.setVisibility(View.GONE);
                    tv_next_hint.setText("请设置6位数字交易密码");
                    tv_error_hint.setText("");
                } else {
                    tv_error_hint.setText(JSONManager.getMsg(jobj));
                }
            }
        }, error);
        requen.add(request);
    }

    public void loginRequen() {
        final Map<String, String> parameters = DataHandler.getParameters("2104");
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            parameters.put("id", user.getCurrUser().getSign());
        }
        parameters.put("confirmPayPwd", DataHandler.encrypt3DES(mPwd));
        parameters.put("payPwd", DataHandler.encrypt3DES(mPwd));
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
        requen.add(request);
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            DataHandler.errorHandler(TradePWD.this, error);
        }
    };

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i("设置密码返回结果" + jobj.toString());
            if (JSONManager.getError(jobj) == -1) {
//                ll.setVisibility(View.GONE);
                Toast.makeText(mContext, "密码设置成功，请妥善保管！", Toast.LENGTH_LONG).show();
                new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        new ReloadUserInfo(TradePWD.this).userRequest();
                        finish();
                        return true;
                    }
                }).sendEmptyMessageDelayed(0, 1000);
            } else {
                tv_error_hint.setText(JSONManager.getMsg(jobj));
            }

        }
    };

    public void hindSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

}
